# 1.引入PIL包中的Image类, 并载入x.png
from PIL import Image




def split_channel(img_in, CHANNEL, out=True,gray=False):
    img = Image.open(img_in)
    p = img.load()
    h, w = img.size

    for i in range(h):    # 扫描像素列表的每一行
        for j in range(w):    # 扫描某一行像素列表的每一列
            (r, g, b) = p[i, j]   # 获取第i行,第j列的像素的RGB
            if(CHANNEL=='r'):
                p[i, j] = (r, 0, 0)  # 只保留R值
                if(gray):
                    p[i, j] = (r, r, r)  # 只保留R值
            elif(CHANNEL == 'g'):
                p[i, j] = (0, g, 0)  # 只保留G值
                if(gray):
                    p[i, j] = (g, g, g)  # 只保留R值
            else:
                p[i, j] = (0, 0, b)  # 只保留B值
                if(gray):
                    p[i, j] = (b, b, b)  # 只保留R值
    if(out and gray):
        img.save(img_in+'-'+CHANNEL+"-gray.png", "PNG")
    elif(out and (not gray)):
        img.save(img_in+'-'+CHANNEL+".png", "PNG")
    img.show()


split_channel("galaxy-full.jpg", 'r')
split_channel("galaxy-full.jpg", 'g')
split_channel("galaxy-full.jpg", 'b')
split_channel("galaxy-full.jpg", 'r',gray=True)
split_channel("galaxy-full.jpg", 'g', gray=True)
split_channel("galaxy-full.jpg", 'b', gray=True)
